package com.example.alladapter.activity;

import android.Manifest;
import android.app.ActivityManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ToggleButton;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.example.alladapter.R;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;

public class ActivityPhoto extends AppCompatActivity {

    private static final int TAKE_PHOTO = 11;// 拍照
    private static final int CROP_PHOTO = 12;// 裁剪图片
    private static final int LOCAL_CROP = 13;// 本地图库
    private File imageFile = null;
    private ToggleButton toggleButton;//显示|隐藏 图片按钮
    private ImageView imageView;//图片显示控件
    private Uri imgUri = null;//图片地址
    private Bitmap bitmap;
    private CharSequence[] items = {"拍照", "相册"};
    private int f = 1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_word);
        getPermissions();
        initeView();
        setListen();

    }

    @Override
    protected void onResume() {
        super.onResume();
        imageView.setImageResource(R.mipmap.img_fs);

    }

    public void getPermissions() {
        String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS};
        ArrayList<String> mPermissionList = new ArrayList<>();
        //逐个判断你要的权限是否已经通过
        mPermissionList.clear();
        for (int i = 0; i < permissions.length; i++)
            if (ContextCompat.checkSelfPermission(ActivityPhoto.this, permissions[i]) != PERMISSION_GRANTED) {
                mPermissionList.add(permissions[i]);//添加还未授予的权限
            }
        if (mPermissionList.size() > 0) {//有权限没有通过，需要申请
            ActivityCompat.requestPermissions(ActivityPhoto.this, permissions, 1100);
        } else {
            f = 1;

        }

    }

    public void exit_app() {
        try {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                ActivityManager activityManager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
                List<ActivityManager.AppTask> appTaskList = null;
                appTaskList = activityManager.getAppTasks();
                for (ActivityManager.AppTask appTask : appTaskList) {
                    appTask.finishAndRemoveTask();
                }
                android.os.Process.killProcess(android.os.Process.myPid());
            }
        } catch (SecurityException e) {
            Log.i("Exception-Security", e.getMessage());
        }
        System.exit(0);

    }

    private void setListen() {
        myClick myClick = new myClick();
        toggleButton.setOnCheckedChangeListener(myClick);
        imageView.setOnLongClickListener(myClick);
    }

    private void initeView() {
        imageView = findViewById(R.id.showzhaopian);
        toggleButton = findViewById(R.id.togglebutton);
    }

    private void takeOrSelect() {
        new AlertDialog.Builder(ActivityPhoto.this)
                .setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = null;
                        switch (which) {
                            case 0:

                                Date date = new Date(System.currentTimeMillis());
                                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                                String StrDate = simpleDateFormat.format(date);
                                File storageDir = null;
                                String storagePath;
                                try {
                                    storagePath = Environment.getExternalStorageDirectory().getAbsolutePath() +
                                            File.separator + "Pictures" + File.separator + "alldapater";

                                    storageDir = new File(storagePath);
                                    storageDir.mkdirs();//创建多层目录，不能创建文件
//                                   imageFile = imageFile.createTempFile("StrDate", ".jpg", storageDir);//创建多个
                                    imageFile=new File(storageDir,"dir.jpg");//创建唯一的一个
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                                imgUri = FileProvider.getUriForFile(ActivityPhoto.this, "com.example.alladapter.fileProvider", imageFile);
                                intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
                                startActivityForResult(intent, TAKE_PHOTO);
                                break;
                            case 1:
                                intent = new Intent(Intent.ACTION_PICK,
                                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                intent.setType("image/*");
                                startActivityForResult(intent, LOCAL_CROP);
                        }
                    }
                }).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TAKE_PHOTO:// 拍照
                if (resultCode == RESULT_OK) {
                    // 创建intent用于裁剪图片
                    Intent intent0 = new Intent("com.android.camera.action.CROP");
                    // 设置数据为文件uri，类型为图片格式
                    intent0.setDataAndType(imgUri, "image/*");
                    // 允许裁剪
                    intent0.putExtra("scale", true);
                    // 指定输出到文件uri中
                    intent0.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
                    // 启动intent，开始裁剪
                    startActivityForResult(intent0, CROP_PHOTO);
                }
                break;
            case LOCAL_CROP:// 系统图库
                if (resultCode == RESULT_OK) {
                    // 创建intent用于裁剪图片
                    Intent intent1 = new Intent("com.android.camera.action.CROP");
                    // 获取图库所选图片的uri
                    Uri uri = data.getData();
                    intent1.setDataAndType(uri, "image/*");
                    //  设置裁剪图片的宽高
                    intent1.putExtra("outputX", 400);
                    intent1.putExtra("outputY", 400);
                    // 裁剪后返回数据
                    intent1.putExtra("return-data", false);
                    intent1.putExtra("crop", "true");
                    intent1.putExtra("aspectX", 1);
                    intent1.putExtra("aspectY", 1);
                    intent1.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
                    intent1.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
                    intent1.putExtra("noFaceDetection", true);
                    intent1.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                    intent1.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    startActivityForResult(intent1, CROP_PHOTO);

                }
                break;
            case CROP_PHOTO:// 裁剪后展示图片
                if (resultCode == RESULT_OK) {
                    try {

                        if (imgUri != null) {
                            // 创建BitmapFactory.Options对象
                            BitmapFactory.Options option = new BitmapFactory.Options();
                            // 属性设置，用于压缩bitmap对象
                            option.inSampleSize = 2;
                            bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imgUri), null, option);
                            // 展示图片
                            imageView.setImageURI(imgUri);
                        }


                        if (data != null) {
                            // 根据返回的data，获取Bitmap对象
                            Bitmap bitmap=null;
                            try {
                                 bitmap = BitmapFactory.decodeStream(this.getContentResolver().openInputStream(data.getData()));
                            }catch (Exception e){
                                e.printStackTrace();
                            }

                            imageView.setImageBitmap(bitmap);

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                break;
        }
    }

    private class myClick implements View.OnClickListener, CompoundButton.OnCheckedChangeListener, View.OnLongClickListener {

        @Override
        public void onClick(View v) {
        }

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            switch (buttonView.getId()) {
                case R.id.togglebutton:
                    if (buttonView.isChecked()) {
                        imageView.setImageBitmap(bitmap);
                    } else {
                        imageView.setImageResource(R.mipmap.img_fs);
                    }
            }

        }

        @Override
        public boolean onLongClick(View v) {
            switch (v.getId()) {
                case R.id.showzhaopian:
                    takeOrSelect();
                    break;
            }
            return false;

        }

    }
}